package MyRedis

import (
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	b "github.com/beego/beego/v2/server/web"
	"github.com/go-redis/redis/v7"
)

var client *redis.Client

func InitRedis() error {
	connStr := b.BConfig.WebConfig.Session.SessionProviderConfig
	config := strings.Split(connStr, ",")
	size, _ := orm.StrTo(config[1]).Int()
	options := &redis.Options{
		Addr:     config[0],
		Password: config[2],
		PoolSize: size,
	}
	client = redis.NewClient(options)
	_, err := client.Ping().Result()
	if err != nil {
		logs.Error("redis连接发生错误：", err)
	}
	return err
}

// 返回值：errMsg
func SetData(key string, value string, seconds int64) string {
	_, err := client.Set(key, value, time.Duration(seconds)*time.Second).Result()
	if err != nil {
		logs.Error("redis写入数据发生错误：", err)
		return err.Error()
	}
	return ""
}

// 返回值：value, errMsg
func GetData(key string) (string, string) {
	value := ""
	err := client.Get(key).Scan(&value)
	if err != nil && err.Error() != "redis: nil" {
		logs.Error("redis读取数据发生错误：", err)
		return "", err.Error()
	}
	return value, ""
}

// 返回值：errMsg
func SetExpire(key string, seconds int64) string {
	_, err := client.Expire(key, time.Duration(seconds)*time.Second).Result()
	if err != nil {
		logs.Error("redis设置有效期发生错误：", err)
		return err.Error()
	}
	return ""
}

// 返回值：seconds, errMsg
func GetExpire(key string) (int64, string) {
	ttl, err := client.TTL(key).Result()
	if err != nil {
		logs.Error("redis读取有效期发生错误：", err)
		return 0, err.Error()
	}
	return int64(ttl.Seconds()), ""
}
